package com.aspectj.aop.utils;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import com.aspectj.aop.root.AndroidAOP;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * desc   : 模版
 * author : chendaning
 * date   : 6/11/21
 */
public class PermissionUtils{
    private static String[] mPermissions;
    private static OnPermissionResult mOnPermissionResult;
    public static void requestPermissionNow(String[] permission, OnPermissionResult onPermissionResult){
        PermissionUtils.mPermissions = permission;
        PermissionUtils.mOnPermissionResult = onPermissionResult;
        AndroidAOP.goTargetActivity(PermissionActivity.class);
    }

    public static class PermissionActivity extends AppCompatActivity {

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Log.v("ASPECT_LOG", "PermissionActivity on create now");
            requestPermissions(mPermissions, 1);
        }


        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            isAllGranted(grantResults);
            finish();
            overridePendingTransition(0,0);
        }
    }

    private static boolean isAllGranted(int[] grantResults){
        for (int result: grantResults) {
            if(result != PackageManager.PERMISSION_GRANTED) {
                mOnPermissionResult.onRequestDenied();
                return false;
            }
        }
        mOnPermissionResult.onRequestSuccess();
        return true;
    }

    public interface OnPermissionResult{
        void onRequestSuccess();
        void onRequestDenied();
    }
}
